<template>
  <section>
    <el-card class="search-card">
      <BasicTableForm ref="formData"
        isScalingBtn
        :colNumOfRow="4"
        :formColumns="formItemList"
        :dataSource="formData"
        :defaultExpandStatus="false"
        :handleSearchForm="handleQueryForm" />
    </el-card>
    <el-card class="table-card">
      <basic-table
        showActionCol
        :showSelectCol="false"
        :loading="tableInfo.loading"
        :columns="tableInfo.columns"
        :dataSource="tableInfo.list"
        :pagination="pagination"
        :tableHeight="460"
        :actionColWidth="200"
        :actionRender="renderTableBtnAction"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange" />
      <!-- <AdvancedTable
        :pagination="pagination"
        :dataSource="tableInfo.list"
        :columns="tableInfo.columns"
        :loading="tableInfo.loading"
        @pageChange="handlePageChange"
        @pageSizeChange="handlePageSizeChange">
          <template #operate="{ row }">
            <el-button type="text" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" @click="handleDeleteStaging(row)">删除</el-button>
            <el-button type="text" @click="handleViewDetail(row)">查看</el-button>
            <el-button type="text" @click="handleViewApprovalFlow(row)">审批流</el-button>
            <el-button type="text" @click="handleWithdraw(row)">取回</el-button>
            <el-button type="primary" @click="handleViewFreight">查看运费</el-button>
          </template>
      </AdvancedTable> -->
    </el-card>
  </section>
</template>

<script>
import { mapGetters } from 'vuex';
import { getBtnsId } from '@/libs/btnsPermission';
import BasicTableForm from '@/components/supplier/BasicForm'; // 表单组件
import BasicTable from '@/components/supplier/BasicTable';
// import AdvancedTable from '@/components/supplier/AdvancedTable'; // 表格组件
// import BaseList from '@/mixins/supplier/baseList'; // 表格Mixin
import {
  queryPendingApprovalListService,
  deleteStagingService,
} from '@/api/supplier/management/pendingApproval';
import {
  getWorkflowJumpUrl,
  retrieveWorkflow,
} from '@/api/supplier/workflow';
import { getHasIndexTableData } from '@/pages/supplier/utils/bizUtils';
import { INITIAL_FIELDS_VALUE, FORM_ITEM_LIST, TABLE_COLUMNS } from './constants';

export default {
  // mixins: [ BaseList ], // 分页数据及方法
  components: {
    BasicTableForm,
    BasicTable,
    // AdvancedTable,
  },
  computed: {
    ...mapGetters('permissions/systemBtns', ['showBtn']),
  },
  data () {
    return {
      formItemList: FORM_ITEM_LIST,
      tableInfo: {
        list: [],
        selection: [],
        columns: TABLE_COLUMNS,
        loading: false
      },
      pagination: {
        current: 1,
        total: 0,
        size: 10
      },
      formData: Object.assign({}, INITIAL_FIELDS_VALUE),
    };
  },
  created () {
    sessionStorage.setItem('buttonId', getBtnsId('查询'));
    this.getTableData();
  },
  methods: {
    handleQueryForm () {
      this.getTableData(1);
    },
    // 页码切换
    handlePageChange (val) {
      this.getTableData(val);
    },
    // 每页条数切换
    handlePageSizeChange (val) {
      this.getTableData(1, val);
    },
    // 获取列表查询参数
    getRequestParams () {
      const {
        supplierCode,
        supplierName,
        supplierClassify,
        mainCategoryId,
        processDocumentStatus,
        processDocumentsOperationType,
        createUser,
        createTime: [ createStartTime, createEndTime ],
        managementAreaId
      } = this.formData
      return {
        supplierCode,
        supplierName,
        supplierClassify,
        mainCategoryId,
        processDocumentStatus,
        processDocumentsOperationType,
        createUser,
        createStartTime,
        createEndTime,
        managementAreaId
      }
    },
    async getTableData (current = this.pagination.current, size = this.pagination.size) {
      this.tableInfo.loading = true
      const params = Object.assign({ current, size }, this.getRequestParams())
      const resp = await queryPendingApprovalListService(params)
      this.tableInfo.loading = false
      if (resp && resp.result) {
        const { records, total, pages } = resp.result
        this.pagination = Object.assign(this.pagination, { current, size, total, pages })
        this.tableInfo.list = getHasIndexTableData(records, this.pagination)
      } else {
        this.tableInfo.list = []
      }
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      // processDocumentStatus 1: 待提交 10:待审批 20:审批通过 30:审批驳回 40:撤回(取回)
      const { id, requestId, supplierId, processDocumentStatus, processDocumentsOperationType } = row
      const notDegrade = ![8, 9].includes(row.processDocumentsOperationType)
      const canEdit = [1, 2, 3, 4, 5, 16, 17, 19, 20, 23, 24].includes(row.processDocumentsOperationType)
      const renderByStatus = () => {
        switch (processDocumentStatus) {
          case 1:
            return <div>
              {notDegrade ? <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button> : null}
              <el-button type="text" disabled={!this.showBtn('删除')} nativeOnClick={() => { this.handleDeleteStaging(row) }}>删除</el-button>
            </div>;
          case 10:
            return <div>
              <el-button type="text" disabled={!this.showBtn('查看')} nativeOnClick={() => { this.handleViewDetail(row) }}>查看</el-button>
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
              {requestId ? <el-button type="text" disabled={!this.showBtn('取回')} nativeOnClick={() => { this.handleWithdraw(row) }}>取回</el-button> : null}
            </div>;
          case 20:
            return <div>
              <el-button type="text" disabled={!this.showBtn('查看')} nativeOnClick={() => { this.handleViewDetail(row) }}>查看</el-button>
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
            </div>;
          case 30:
            return <div>
              {notDegrade ? <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button> : null}
              {requestId ? <el-button type="text" disabled={!this.showBtn('审批流')} nativeOnClick={() => { this.handleViewApprovalFlow(requestId) }}>审批流</el-button> : null}
              <el-button type="text" disabled={!this.showBtn('删除')} nativeOnClick={() => { this.handleDeleteStaging(row) }}>删除</el-button>
            </div>;
          case 40:
            return <div>
              {canEdit ? <el-button type="text" disabled={!this.showBtn('编辑')} nativeOnClick={() => { this.handleEdit(row) }}>编辑</el-button> : null}
              <el-button type="text" disabled={!this.showBtn('删除')} nativeOnClick={() => { this.handleDeleteStaging(row) }}>删除</el-button>
            </div>;
          default:
            return <div></div>;
        }
      }
      return renderByStatus()
    },
    // 编辑
    handleEdit (row) {
      const { id, supplierId, processDocumentsOperationType } = row
      /**
       * 1：供应商新增，2：供应商编辑，3：线索转潜在，4：线索转合格，5：潜在转合格，6：加入黑名单，7：移出黑名单
       * ，8：合格降级潜在 9：潜在降级线索，10：淘汰供应商，11：激活供应商，12：运费新增，13：运费编辑  14:考察计划  15:考察报告
       * 16: 潜在供应商新增 17:潜在供应商修改  18:更换业务对接人  19:特殊供应商新增 20:特殊供应商编辑
       * 23: 开票转合格供应商, 24: 开票转潜在供应商, 25: 合格供应商淘汰, 26: 合格供应商激活, 27: 特殊供应商淘汰, 28: 特殊供应商激活
       */
      let jumpName = ''
      switch (processDocumentsOperationType) {
        case 1:
          jumpName = 'addQualifiedSupplier'
          break;
        case 2:
        case 23: // 开票转合格供应商
          jumpName = 'editQualifiedSupplier'
          break;
        case 3:
          jumpName = 'corventClues2Potential'
          break;
        case 4:
          jumpName = 'corventClues2Qualified'
          break;
        case 5:
          jumpName = 'corventPotential2Qualified'
          break;
        case 12:
        case 13:
          jumpName = 'addFreight'
          break;
        case 16:
          jumpName = 'addPotentialSupplier'
          break;
        case 17:
        case 24: // 开票转潜在供应商
          jumpName = 'editPotentialSupplier'
          break;
        case 19:
          jumpName = 'addSpecialSupplier'
          break;
        case 20:
          jumpName = 'editSpecialSupplier'
          break;
      }
      this.$router.push({ name: jumpName, query: { processId: id, id: supplierId } });
    },
    // 删除暂存
    handleDeleteStaging (data) {
      this.$confirm('确定要删除吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableInfo.loading = true
        deleteStagingService({ id: data.id }).then(() => {
          this.tableInfo.loading = false
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getTableData()
        })
          .catch((error) => {
            this.tableInfo.loading = false
            console.error('error :>> ', error);
          })
      }).catch(() => {});
    },
    // 查看
    handleViewDetail (row) {
      /**
       * 1：供应商新增，2：供应商编辑，3：线索转潜在，4：线索转合格，5：潜在转合格，6：加入黑名单，7：移出黑名单
       * ，8：合格降级潜在 9：潜在降级线索，10：淘汰供应商，11：激活供应商，12：运费新增，13：运费编辑  14:考察计划  15:考察报告
       * 16: 潜在供应商新增 17:潜在供应商修改  18:更换业务对接人  19:特殊供应商新增 20:特殊供应商编辑
       */
      const { id, supplierId, supplierClassify, processDocumentStatus: status, processDocumentsOperationType: type } = row
      const query = {
        id: supplierId,
        status,
        type
      }
      if (status !== 20) {
        query.processId = id
      }
      switch (type) {
        case 1:
        case 2:
          if (supplierClassify === 40899) {
            // 线索
            this.$router.push({ name: 'viewCluesSupplier', query });
          }
          if (supplierClassify === 40332) {
            // 合格
            this.$router.push({ name: 'viewQualifiedSupplier', query });
          }
          break;
        case 4:
        case 5:
        case 23:
          // 合格
          this.$router.push({ name: 'viewQualifiedSupplier', query });
          break;
        case 3:
        case 16:
        case 17:
        case 24:
          // 潜在
          this.$router.push({ name: 'viewPotentialSupplier', query });
          break;
        case 19:
        case 20:
          // 特殊
          this.$router.push({ name: 'viewSpecialSupplier', query });
          break;
        case 6:
        case 7:
        case 10:
        case 11:
        case 25:
        case 26:
        case 27:
        case 28:
          this.handleViewSupplier(type, id, supplierClassify)
          break;
        case 12:
        case 13:
          this.handleViewFreight(id)
          break;
        case 18:
          // 更换业务对接人
          this.$router.push({ name: 'batchHandover', query: { processId: id } });
          break;
        default:
          console.log('processDocumentsOperationType', type)
          break;
      }
      // this.$router.push({ path: '/supplier/management/view', query: { id: data.id } });
    },
    // 查看运费
    handleViewFreight (processId) {
      this.$router.push({ name: 'viewFreightDetail', query: { processId } });
    },
    // 查看供应商
    handleViewSupplier (type, processId, supplierClassify) {
      this.$router.push({ name: 'viewSupplier', query: { type, processId, supplierClassify } });
    },
    // 查看审批流
    handleViewApprovalFlow (requestId) {
      // 动态获取工作流跳转地址
      getWorkflowJumpUrl({ requestId }).then(({ result }) => {
        window.open(result, '_blank')
      })
    },
    // 取回单据
    handleWithdraw (data) {
      this.$confirm('确定要取回当前单据吗?', '取回', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableInfo.loading = true
        retrieveWorkflow({ oaRequestId: data.requestId, itemUserId: data.createUserId })
          .then(({ result }) => {
            this.tableInfo.loading = false
            this.$message({
              type: 'success',
              message: '取回成功!'
            });
            this.getTableData()
          })
          .catch((error) => {
            this.tableInfo.loading = false
            console.error('error :>> ', error);
          })
      }).catch(() => {
        this.tableInfo.loading = false
      });
    },
  },
}
</script>
